package com.chain.qs.modules.biz.service;

import com.chain.qs.common.schedule.QuartzJobBean;
import com.chain.qs.common.utils.TaskUtils;
import org.quartz.*;
import org.quartz.impl.StdScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

public abstract class JobOperationService extends org.springframework.scheduling.quartz.QuartzJobBean{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name="schedulerFactoryBean")
    private StdScheduler scheduler;

    /**
     * 初始化任务  增加与更新操作
     *
     * @param job
     * @throws SchedulerException
     */
    public boolean initJob(QuartzJobBean job) throws SchedulerException {
        if (job == null || !(QuartzJobBean.STATUS_RUNNING == job.getJobStatus())) {
            return false;
        }
        if (!TaskUtils.isValidExpression(job.getCronExpression())) {
            logger.error("时间表达式错误（" + job.getJobName() + "," + job.getJobGroup() + "）," + job.getCronExpression());
            return false;
        } else {
//            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            // 任务名称和任务组设置规则：    // 名称：task_1 ..    // 组 ：group_1 ..
            TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 不存在，创建一个
            if (null == trigger) {
                JobDetail jobDetail = JobBuilder.newJob(this.getClass()).withIdentity(job.getJobName(), job.getJobGroup()).build();
                jobDetail.getJobDataMap().put("scheduleJob", job);

                // 表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
                // 按新的表达式构建一个新的trigger
                trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
                scheduler.scheduleJob(jobDetail, trigger);
            } else {     // trigger已存在，则更新相应的定时设置
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
                // 按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
                // 按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        }
        return true;
    }

    public boolean delJob(QuartzJobBean job) throws SchedulerException {
        if (job == null || !(QuartzJobBean.STATUS_RUNNING == job.getJobStatus())) {
            return false;
        }
//        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        // 任务名称和任务组设置规则：    // 名称：task_1 ..    // 组 ：group_1 ..
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        // 不存在，创建一个
        if (null != trigger) {
            JobDetail jobDetail = JobBuilder.newJob(this.getClass()).withIdentity(job.getJobName(), job.getJobGroup()).build();
            jobDetail.getJobDataMap().put("scheduleJob", job);
            scheduler.deleteJob(jobDetail.getKey());
        }
        return true;
    }
}
